package com.hqyj.shop.service.impl;

import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hqyj.shop.config.PayConfig;
import com.hqyj.shop.mapper.SalesMapper;
import com.hqyj.shop.pojo.*;
import com.hqyj.shop.mapper.OrderInfoMapper;
import com.hqyj.shop.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hqyj.shop.util.JwtUtil;
import com.hqyj.shop.util.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author rock
 * @since 2024-10-16 10:45:08
 */
@Slf4j
@Service

public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    //注入支付宝的二维码付款对象服务
    @Autowired
    AlipayClient alipayClient;

    @Autowired
    PayConfig payConfig;

    @Resource
    OrderInfoMapper orderInfoMapper;

    @Autowired
    OrderDetailService orderDetailService;

    @Resource
    SalesService salesService;

    @Resource
    SalesMapper salesMapper;

    @Autowired
    GoodsInfoService goodsInfoService;

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public String createQrCode(MyQrCode code) {

        //发送请求
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        //把MyQrCode对象参数转换成字符串类型
        ObjectMapper mapper = new ObjectMapper();
        try {
            String str = mapper.writeValueAsString(code);
            //设置请求参数
            request.setNotifyUrl(payConfig.getNotifyUrl());
            request.setBizContent(str);
            //发送请求并且获取请求的响应信息
            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            boolean is = response.isSuccess();
            log.info("是否成功：{}",response.isSuccess());
            System.out.println(is);
            if(is){
                return response.getQrCode();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        //交易失败给交易失败的链接
        return "http://www.baidu.com";
    }

    @Override
    @Transactional
    public ResultVo insert(OrderInfo orderInfo, HttpServletRequest request) {
        //获取Token
        String token = request.getHeader("Authorization");
        //获取用户名
        String name = JwtUtil.getClaimByName(token,"userName").asString();
        //获取userId
        String userId = JwtUtil.getAudience(token);
        //订单插入
        orderInfo.setUserId(Integer.parseInt(userId));
        int num = orderInfoMapper.insert(orderInfo);
        if(num > 0){
            //订单详情
            List<OrderDetail> orderDetails = orderInfo.getOrderDetailList();
            if(orderDetails.size()> 0){
                    for(OrderDetail orderDetail:orderDetails){
                        orderDetail.setOrderId(orderInfo.getOrderId());
                        orderDetail.setCreateTime(new Date());
                    }
                //批量插入
               boolean is = orderDetailService.saveBatch(orderDetails);
                if(is){
                    List<Sales> salesList = orderInfo.getSalesList();
                    for(Sales s:salesList){
                        s.setSalesTime(new Date());
                    }
                    boolean a = salesService.saveBatch(salesList);
                    if(a){
                        log.info("插入成功");
                        return ResultVo.success("订单插入成功",orderInfo.getOrderId());
                    }
                }
            }

        }
        log.info("插入失败");

        return ResultVo.error();
    }

    //业务：1 更改订单的支付状态，2 更改销售的支付状态，3 修改库存  4 清空购物车
   //   subject = 1,2&2,2&3
    @Override
    @Transactional
    public ResultVo updateOrder(String orderNo, String subject) {
        //解析subject字符串
        String arr[] = subject.split("&");
        //商品id集合
        List<String> goodsList = new ArrayList<>();
        //商品购买数量集合
        List<String> goodsNumList = new ArrayList<>();
        if(arr.length > 0){
            String goodsIds[] = arr[0].split(",");
            if(goodsIds.length>0){
                 for(int i=0;i<goodsIds.length;i++){
                     goodsList.add(goodsIds[i]);
                 }
            }
            String goodsNumIds[] = arr[1].split(",");
            if(goodsNumIds.length>0){
                for(int i=0;i<goodsNumIds.length;i++){
                    goodsNumList.add(goodsNumIds[i]);
                }
            }

        }
        //1 更改订单的支付状态
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderId(orderNo);
        //修改为已支付
        orderInfo.setOrderStatus(1);;
        int num = orderInfoMapper.updateById(orderInfo);
        if(num > 0){
            //3 修改库存
            List<GoodsInfo> goodsInfoList = new ArrayList<>();
            for(int i=0;i<goodsList.size();i++){
                GoodsInfo g = new GoodsInfo();
                g.setGoodsId(Integer.parseInt(goodsList.get(i)));
                QueryWrapper<GoodsInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("goods_id",goodsList.get(i));
                GoodsInfo good =goodsInfoService.getOne( queryWrapper);
                //计算库存
                int s = good.getStockNum()-Integer.parseInt(goodsNumList.get(i));
                g.setStockNum(s);
                goodsInfoList.add(g);
            }
            boolean is = goodsInfoService.updateBatchById(goodsInfoList);
            if(is){
                //  更改销售的支付状态
                    int m = 0;
                    for(int i=0;i<goodsList.size();i++){
                          Sales s  = new Sales();
                          s.setPaymentStatus("1");
                          //用for修改会消耗更多数据库连接，如果数据量比较大的情况，建议用批量做
                          //如果不能用批量来做，建议处理业务加入消息队里来处理，减轻数据库访问压力
                          QueryWrapper<Sales> queryWrapper = new QueryWrapper<>();
                          queryWrapper.eq("goods_id",goodsList.get(i));
                           m = salesMapper.update(s,queryWrapper);
                      }
                    if(m > 0){
                        // 4 清空购物车
                        redisTemplate.delete("car:"+arr[2]);
                        return ResultVo.success();

                }
            }
        }
        return ResultVo.error();
    }
}
